package com.beiye.drivertransport.fragment;


import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.SpecifiedLearningBusinessDetailsActivity;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.SpecifiedLearningBusinessBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.utils.UserManger;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//单位人员安全学习
public class SpecifiedLearningCompanyFragment extends TwoBaseFgt {

    ExpandableListView specified_lv;

    TextView tv_specified_learning;

    View empty_view;
//    @Bind(R.id.img_specified_learning)
//    TextView img_specified_learning;
//    ArrayList<LoginUserBean.DataBean.CurUserOrgBean> cusList = new ArrayList<>();
//    private PopupWindow mPopWindow;
//    private PopWindowApt popWindowApt;
    private MyExpandableListViewAdapter adapter;
    private List<SpecifiedLearningBusinessBean.RowsBean> ParentList = new ArrayList<>();
    Map<SpecifiedLearningBusinessBean.RowsBean, List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean>> dataset = new HashMap<>();
    ArrayList<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> sbcourselist = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.fragment_specified_learning_company;

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void initData() {
        specified_lv = (ExpandableListView) getActivity().findViewById(R.id.specified_companyexpandablelistview);
        tv_specified_learning = (TextView) getActivity().findViewById(R.id.tv_specified_learning);
        empty_view = (View) getActivity().findViewById(R.id.empty_view);

        //选中公司方法
        initCompany();

        initUi();



    }

    private void initCompany() {
//        LoginUserBean userInfo = UserManger.getUserInfo();
//        LoginUserBean.DataBean data = userInfo.getData();
//        if (data == null) {
//            return;
//        }
//        String userId = data.getUserId();
//        LogUtils.e("userId", userId);//6E7119CD-699B-49A2-A0B0-045D0BF7B8C0
//        List<LoginUserBean.DataBean.CurUserOrgBean> curuserOrglist = data.getCur_userOrg();
//
//        if (curuserOrglist.size() == 0) {
//            img_specified_learning.setVisibility(View.INVISIBLE);
//            return;
//        }
//        cusList.clear();
//        for (int i = 0; i < curuserOrglist.size(); i++) {
//            if (curuserOrglist.get(i).getMark() != 2) {
//                cusList.add(curuserOrglist.get(i));
//            }
//        }
//        String orgName = cusList.get(0).getOrgName();
//        String orgId = cusList.get(0).getOrgId();
//        int minPer = cusList.get(0).getMinPer();
//        int readInterval = cusList.get(0).getReadInterval();
//        int mark = cusList.get(0).getMark();

        String     orgName = getArguments().getString("orgName");
        String    orgId = getArguments().getString("orgId");
        int  minPer = getArguments().getInt("minPer");
        int  readInterval = getArguments().getInt("readInterval");
        int  mark = getArguments().getInt("Mark");



        SharedPreferences spp = getActivity().getSharedPreferences("orgId12",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spp.edit();
        edit.putInt("minPer", minPer);
        edit.commit();
        //存储一份readInterval文件
        SharedPreferences sp = getActivity().getSharedPreferences("readInterval7",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("readInterval", readInterval);
        editor.commit();
        SharedPreferences sppp = getActivity().getSharedPreferences("Mark7", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor2 = sppp.edit();
        editor2.putInt("Mark", mark);
        editor2.commit();
        tv_specified_learning.setText(orgName);
        initUiData(orgId);

//        popWindowApt = new PopWindowApt(getActivity(), cusList, R.layout.popwindow_item_layout);
//        if (popWindowApt.getCount() == 1) {
//            img_specified_learning.setVisibility(View.INVISIBLE);
//        } else {
//            img_specified_learning.setVisibility(View.VISIBLE);
//        }

//        OkGo.get(AppInterfaceConfig.BASE_URL+"vehicle/vehicleOrg/"+userId)     // 请求方式和请求url
//                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
//                .execute(new StringCallback() {
//
//
//                    @Override
//                    public void onSuccess(String result, Call call, Response response) {
//
//                        CompanyBean companyBean = JSON.parseObject(result, CompanyBean.class);
//                        List<CompanyBean.RowsBean> rows = companyBean.getRows();
//
//                        if(rows.size()==0)
//                        {
//                            LoginUserBean userInfo = UserManger.getUserInfo();
//                            String orgName = userInfo.getOrgName();
//                            String orgId = userInfo.getOrgId();
//                            CompanyBean.RowsBean temp = new CompanyBean.RowsBean();
//                            temp.setOrgId(userInfo.getOrgId());
//                            temp.setOrgName(userInfo.getOrgName());
//                            rows.add(temp);
//                            tv_specified_learning.setText(orgName);
//                            initUiData(orgId);
//                        }else{
//
//                            tv_specified_learning.setText(rows.get(0).getOrgName());
//                            initUiData(rows.get(0).getOrgId());
//                        }
//
//                        popWindowApt = new PopWindowApt(getActivity(),rows,R.layout.popwindow_item_layout);
////                        //存储一份readInterval文件
////                        SharedPreferences sp = getActivity().getSharedPreferences("orgId1",
////                                Context.MODE_PRIVATE);
////                        SharedPreferences.Editor editor = sp.edit();
////                        editor.putString("orgId", rows.get(0).getOrgId());
////                        editor.commit();
//
//                    }
//                });

    }

//    private void showPopupWindow() {
//        //设置contentView
//        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_layout, null);
//        mPopWindow = new PopupWindow(contentView,
//                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
//        //设置各个控件的点击响应
//        ListView lv_company = (ListView) contentView.findViewById(R.id.lv_company);
//        lv_company.setAdapter(popWindowApt);
//        mPopWindow.showAtLocation(tv_specified_learning, Gravity.CENTER, 0, 0);
////        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
////        mPopWindow.showAsDropDown(tv_specified_learning);
//        lv_company.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                if (popWindowApt != null) {
//
//                    String orgName = popWindowApt.getItem(position).getOrgName();
//                    String orgId = popWindowApt.getItem(position).getOrgId();
//                    int minPer = popWindowApt.getItem(position).getMinPer();
//                    int readInterval = popWindowApt.getItem(position).getReadInterval();
//                    int mark = popWindowApt.getItem(position).getMark();
//                    SharedPreferences spp = getActivity().getSharedPreferences("orgId12",
//                            Context.MODE_PRIVATE);
//                    SharedPreferences.Editor edit = spp.edit();
//                    edit.putInt("minPer", minPer);
//                    edit.commit();
//                    //存储一份readInterval文件
//                    SharedPreferences sp = getActivity().getSharedPreferences("readInterval7",
//                            Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor = sp.edit();
//                    editor.putInt("readInterval", readInterval);
//                    editor.commit();
//                    SharedPreferences sppp = getActivity().getSharedPreferences("Mark7", Context.MODE_PRIVATE);
//                    SharedPreferences.Editor editor2 = sppp.edit();
//                    editor2.putInt("Mark", mark);
//                    editor2.commit();
//                    mPopWindow.dismiss();
//                    tv_specified_learning.setText(orgName);
//                    initUiData(orgId);
//
//                }
//            }
//        });
//    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences spp = getActivity().getSharedPreferences("orgId12",
                Context.MODE_PRIVATE);
        String orgId = spp.getString("orgId", "");

        initUiData(orgId);
    }

    public void initUiData(String orgId) {
        LoginUserBean userInfo = UserManger.getUserInfo();
        LoginUserBean.DataBean data = userInfo.getData();
        if (data == null) {
            return;
        }
        String userId = data.getUserId();

//        //存储一份readInterval文件
//        SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                Context.MODE_PRIVATE);
//        int  readInterval = sp.getInt("readInterval", 0);
//        //存储一份orgId文件
        SharedPreferences spp = getActivity().getSharedPreferences("orgId12",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = spp.edit();
        edit.putString("orgId", orgId);
        edit.commit();

        new Login().getSpecifiedBusinessLearning(orgId, userId, 1, 1, 1, 1000, this, 1);

    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        if (what == 1) {

            SpecifiedLearningBusinessBean specifiedLearningBusinessBean = JSON.parseObject(result, SpecifiedLearningBusinessBean.class);
            List<SpecifiedLearningBusinessBean.RowsBean> rows = specifiedLearningBusinessBean.getRows();
            ParentList.clear();
            dataset.clear();
            ParentList.addAll(rows);
            for (int i = 0; i < ParentList.size(); i++) {
                List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> courseList = ParentList.get(i).getCourseList();
                dataset.put(ParentList.get(i), courseList);
            }
            adapter = new MyExpandableListViewAdapter(getContext(), ParentList, dataset);
            specified_lv.setAdapter(adapter);

        }
        //else if (what == 2) {
//            if(!CameraCanUseUtils.isCameraCanUse()) {
//                ToastUtil.showShortToast(getActivity(),"请到手机设置界面里找驾运宝允许开启照相");
//                dialog.dismiss();
//                return;
//            }
//
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            if (code == 0) {
//                //存储一份readInterval文件
//                SharedPreferences spp = getActivity().getSharedPreferences("prejobTraingtcSn",
//                        Context.MODE_PRIVATE);
//                int tcSn = spp.getInt("tcSn", 0);
//                int otcSn = spp.getInt("otcSn", 0);
//                Bundle bundle = new Bundle();
//                bundle.putInt("tcsn", tcSn);
//                bundle.putInt("otcSn", otcSn);
//                SharedPreferences sp = getActivity().getSharedPreferences("readInterval",
//                        Context.MODE_PRIVATE);
//                int readInterval = sp.getInt("readInterval", 0);
//                bundle.putInt("readInterval", readInterval);
//                //存储一份orgId文件
//                SharedPreferences sppp = getActivity().getSharedPreferences("orgId5",
//                        Context.MODE_PRIVATE);
//                String  orgId = sppp.getString("orgId","");
//                bundle.putString("orgId",orgId);
//                startActivity(SpecifiedLearningCourseDetailsActivity.class, bundle);
//
//
//            }
//            dialog.dismiss();
//        }
        super.onSuccess(result, call, response, what);
    }

    private void initUi() {

        specified_lv.setGroupIndicator(null);//去掉箭头
        specified_lv.setEmptyView(empty_view);
        specified_lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {

                SharedPreferences sp1 = getActivity().getSharedPreferences("Mark7", Context.MODE_PRIVATE);
                int mark = sp1.getInt("Mark", 1);
                if (mark == 0) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
                    builder1.setMessage("您已被企业管理员禁用,请联系企业管理员");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });
                    builder1.create().show();

                } else {
                    if (!CameraCanUseUtils.isCameraCanUse()) {

                        ToastUtil.showShortToast(getActivity(), "请到手机设置界面里找驾运宝允许开启照相");
                    } else {
                        if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getCreationDate() == 0) {
                            showLoadingDialog("正在加载");
                            int tcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getTcSn();
                            int atcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getSn();
                            int atpSn = ParentList.get(groupPosition).getSn();
                            List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean> courseList = ParentList.get(groupPosition).getCourseList();
                            sbcourselist.clear();
                            for (int i = 0; i < courseList.size(); i++) {
                                if (courseList.get(i).getSn() != atcSn && courseList.get(i).getCreationDate() == 0) {
                                    sbcourselist.add(courseList.get(i));
                                }
                            }

                            SharedPreferences sp = getActivity().getSharedPreferences("readInterval7",
                                    Context.MODE_PRIVATE);
                            int readInterval = sp.getInt("readInterval", 0);
                            //存储一份orgId文件
                            SharedPreferences sppp = getActivity().getSharedPreferences("orgId12",
                                    Context.MODE_PRIVATE);
                            String orgId = sppp.getString("orgId", "");
                            int minPer = sppp.getInt("minPer", 0);
                            Bundle bundle = new Bundle();
                            bundle.putInt("readInterval", readInterval);
                            bundle.putInt("tcsn", tcSn);
                            bundle.putInt("atcSn", atcSn);
                            bundle.putInt("atpSn", atpSn);
                            bundle.putString("orgId", orgId);
                            bundle.putInt("minPer", minPer);
                            bundle.putSerializable("sbcourselist", (Serializable) sbcourselist);
                            startActivity(SpecifiedLearningBusinessDetailsActivity.class, bundle);

                        } else if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getCreationDate() > 0) {

                            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getContext());
                            builder1.setMessage("该课程已学习");
                            builder1.setTitle("提示:");
                            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    ;
                                    //设置你的操作事项
                                }
                            });
                            builder1.create().show();

                        }
                    }
                }
                //  initcoursesupermaketCheckData(tcSn,otcSn);

                return true;
            }
        });

    }

    private class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

        private Context context;
        private List<SpecifiedLearningBusinessBean.RowsBean> ParentList;
        private Map<SpecifiedLearningBusinessBean.RowsBean, List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean>> dataset;

        public MyExpandableListViewAdapter(Context context, List<SpecifiedLearningBusinessBean.RowsBean> ParentList, Map<SpecifiedLearningBusinessBean.RowsBean, List<SpecifiedLearningBusinessBean.RowsBean.CourseListBean>> dataset) {
            this.context = context;
            this.ParentList = ParentList;
            this.dataset = dataset;
        }


        //  获得某个父项的某个子项
        @Override
        public Object getChild(int parentPos, int childPos) {

            return dataset.get(ParentList.get(parentPos)).get(childPos);

        }

        //  获得父项的数量
        @Override
        public int getGroupCount() {
            return dataset.size();
        }

        //  获得某个父项的子项数目
        @Override
        public int getChildrenCount(int parentPos) {

            return dataset.get(ParentList.get(parentPos)).size();
        }

        //  获得某个父项
        @Override
        public Object getGroup(int parentPos) {
            return dataset.get(ParentList.get(parentPos));
        }

        //  获得某个父项的id
        @Override
        public long getGroupId(int parentPos) {
            return parentPos;
        }

        //  获得某个父项的某个子项的id
        @Override
        public long getChildId(int parentPos, int childPos) {
            return childPos;
        }

        //  按函数的名字来理解应该是是否具有稳定的id，这个方法目前一直都是返回false，没有去改动过
        @Override
        public boolean hasStableIds() {
            return false;
        }

        //  获得父项显示的view
        @Override
        public View getGroupView(int parentPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.parent_item, null);
            }
            view.setTag(R.layout.parent_item, parentPos);
            view.setTag(R.layout.child_item, -1);

            ImageView img_parent = (ImageView) view.findViewById(R.id.img_parent);
            TextView parent_line = (TextView) view.findViewById(R.id.parent_line);
            TextView tv_title = (TextView) view.findViewById(R.id.tv_parent);
            TextView tv_date = (TextView) view.findViewById(R.id.tv_parent2);
            LinearLayout re_nodata = (LinearLayout) view.findViewById(R.id.re_nodata);//子类无数据
            if (ParentList != null && parentPos < ParentList.size()) {
                tv_title.setText(ParentList.get(parentPos).getPlanName());
                long beginDate = ParentList.get(parentPos).getBeginDate();
                long endDate = ParentList.get(parentPos).getEndDate();
                //mill为你龙类型的时间戳
                Date date1 = new Date(beginDate);
                Date date2 = new Date(endDate);
                String begin = "";
                String end = "";
                try {
                    //yyyy表示年MM表示月dd表示日
                    //yyyy-MM-dd是日期的格式，比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    //进行格式化
                    begin = sdf.format(date1);
                    end = sdf.format(date2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tv_date.setText(begin + "--" + end);
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) parent_line.getLayoutParams(); //取控件textView当前的布局参数
                if (b)//判断展开
                {
                    if (ParentList.get(parentPos).getCourseList().size() == 0) {
                        re_nodata.setVisibility(View.VISIBLE);
                    }
                    img_parent.setImageResource(R.mipmap.jianhao);
                    linearParams.height = 3;// 控件的高强制设成3
                    parent_line.setLayoutParams(linearParams);

                } else {
                    re_nodata.setVisibility(View.GONE);
                    img_parent.setImageResource(R.mipmap.jiahao);
                    linearParams.height = 13;// 控件的高强制设成16
                    parent_line.setLayoutParams(linearParams);
                }
            }


            return view;
        }

        //  获得子项显示的view
        @Override
        public View getChildView(int parentPos, int childPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.child_item, null);
            }
            view.setTag(R.layout.parent_item, parentPos);
            view.setTag(R.layout.child_item, childPos);
            TextView tv_ttName = (TextView) view.findViewById(R.id.tv_child);
            TextView tv_courseName = (TextView) view.findViewById(R.id.tv_child2);
            TextView tv_courseLength = (TextView) view.findViewById(R.id.tv_child3);
            ImageView tv_studyState = (ImageView) view.findViewById(R.id.tv_child4);
            tv_ttName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getTtName());
            tv_courseName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getCourseName());
            tv_courseLength.setText("课程时长:" + dataset.get(ParentList.get(parentPos)).get(childPos).getCourseLength() + "分钟");
            if (dataset.get(ParentList.get(parentPos)).get(childPos).getCreationDate() == 0) {
                tv_studyState.setImageResource(R.mipmap.wxx);
            } else if (dataset.get(ParentList.get(parentPos)).get(childPos).getCreationDate() > 0) {
                tv_studyState.setImageResource(R.mipmap.yxx);

            }


            return view;
        }

        //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }

    @Override
    public void requestData() {

    }

    @Override
    public void onUserVisible() {

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }
}
